package trystero.lib.component.parser;

import java.util.Vector;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONTokener;

import trystero.lib.component.SubscriptionList;
import trystero.lib.component.ReaderSubscription;
import trystero.lib.component.ReaderTag;

public class SubscriptionListParser
{
   InputStream stream;

   public SubscriptionListParser(String json)
   {
      this.stream = stream;
   }

   public SubscriptionList parse() throws Exception
   {
      JSONTokener t = new JSONTokener(new InputStreamReader(this.stream));
      JSONObject o = new JSONObject(t);
      return this.parse(json);
   }

   public SubscriptionList parse(String json) throws Exception
   {
      SubscriptionList list = new SubscriptionList();

      JSONArray subscriptions = (JSONArray)o.get("subscriptions");
      list.subscriptions(this.parseSubscriptionVector(subscriptions));

      return list;
   }

   public Vector parseSubscriptionVector(JSONArray a) throws Exception
   {
      Vector v = new Vector();

      for(int i = 0; i < a.length(); i++)
      {
	 ReaderSubscription subscription = this.parseSubscription((JSONObject)a.get(i)); 
	 v.add(subscription);
      }

      return v;
   }

   public ReaderSubscription parseSubscription(JSONObject o) throws Exception
   {
      ReaderSubscription subscription = new ReaderSubscription();

      subscription.id((String)o.get("id"));
      subscription.title((String)o.get("title"));
      subscription.categories(this.parseTagVector((JSONArray)o.get("categories")));
      subscription.sortid((String)o.get("sortid"));
      subscription.firstItem(Long.parseLong((String)o.get("firstitemmsec")));

      return subscription;
   }

   public Vector parseTagVector(JSONArray a) throws Exception
   {
      Vector v = new Vector();

      for(int i = 0; i < a.length(); i++)
      {
	 ReaderTag tag = this.parseTag((JSONObject)a.get(i)); 
	 v.add(tag);
      }

      return v;
   }

   public ReaderTag parseTag(JSONObject o) throws Exception
   {
      ReaderTag tag = new ReaderTag();

      tag.tag((String)o.get("id"));
      tag.label((String)o.get("label"));

      return tag;
   }
}
